package com.loongtech.bi.action.advertisment;

import com.loongtech.bi.advertisment.controller.BaseAdvAction;
import com.loongtech.bi.advertisment.model.AdvWarningData;
import com.loongtech.bi.advertisment.model.AdvWarningInputData;
import com.loongtech.bi.advertisment.service.PayUserService;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.core.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * ClassName: RTWarnDataAction
 * 
 * @Description: 实时广告异常数据
 * @author liuchen
 * @date 2017-7-27 下午5:50:30
 */
@Controller
@Scope("prototype")
@RequestMapping("/market/warnDataMarket")
public class RTWarnDataAction extends BaseAdvAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource(name = "payUserService")
	private PayUserService payUserService;

    @Autowired
    private SysUserManager sysUserManager;

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

			result.put("res", "0");
			result.put("channelName", getChannelName());
			result.put("agent", getAgent());
			result.put("platform", getPlatform());
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
			@RequestParam String eday, @RequestParam String agent, @RequestParam String platform,
			@RequestParam String channelName, @RequestParam String seltype, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }

			sday = sday.replaceAll("-", "");
			eday = eday.replaceAll("-", "");
            String[] channelNames = "".equals(channelName) ? getChannelName().toArray(new String[getChannelName().size()]) : Utils.matchesString(channelName).split(",");
            String[] agents = "".equals(agent) ? getAgent().toArray(new String[getAgent().size()]) : Utils.matchesString(agent).split(",");
            String[] platforms = "".equals(platform) ? getPlatform().toArray(new String[getPlatform().size()]) : Utils.matchesString(platform).split(",");

            List<AdvWarningData> warningDatas = payUserService.getListWarningData(sday, eday, channelNames, agents,
					platforms, seltype);
			AdvWarningData total = new AdvWarningData();
			Integer actives = 0;
			Integer warnActices = 0;
			for (AdvWarningData d : warningDatas) {
				actives += d.getActive();
				warnActices += d.getWarnActice();
			}
			total.setLogday("Total");
			total.setActive(actives);
			total.setWarnActice(warnActices);
			DecimalFormat df = new DecimalFormat("#.####");
			total.setRate(actives == 0 ? 0 : Double.valueOf(df.format((double) warnActices / actives)));
			result.put("res", "0");
			result.put("warningDatas", warningDatas);
			result.put("total", total);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "searchInput.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void searchInput(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
			@RequestParam String eday, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }

			sday = sday.replaceAll("-", "");
			eday = eday.replaceAll("-", "");
			List<AdvWarningInputData> warningInputDatas = payUserService.getListWarningInputData(sday, eday);
			result.put("res", "0");
			result.put("warningInputDatas", warningInputDatas);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	@RequestMapping(value = "excel.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void excel(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
			@RequestParam String eday, @RequestParam String agent, @RequestParam String platform,
			@RequestParam String channelName, @RequestParam String seltype, @RequestParam String uid, String callback) {
		try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }
			sday = sday.replaceAll("-", "");
			eday = eday.replaceAll("-", "");
            String[] channelNames = "".equals(channelName) ? getChannelName().toArray(new String[getChannelName().size()]) : Utils.matchesString(channelName).split(",");
            String[] agents = "".equals(agent) ? getAgent().toArray(new String[getAgent().size()]) : Utils.matchesString(agent).split(",");
            String[] platforms = "".equals(platform) ? getPlatform().toArray(new String[getPlatform().size()]) : Utils.matchesString(platform).split(",");

            List<List<List<String>>> warningDatas = payUserService.getExcelWarningData(sday, eday, channelNames,
					agents, platforms, seltype);
			List<String> columns = Arrays.asList("激活数据", "异常mac");
			List<List<String>> columnnames = Arrays.asList(Arrays.asList("日期", "渠道名称", "代理", "激活数", "异常数", "异常比例"),
					Arrays.asList("日期", "mac"));

			exportExcel(warningDatas, columns, columnnames, "adv_warning_data_" + System.currentTimeMillis(), response);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			e.printStackTrace();
		}
	}
}
